# coding:utf-8
import os
import re
from sys import executable
from subprocess import Popen, CREATE_NEW_CONSOLE
from airtest.core.api import connect_device
from airtest.core.api import set_current

def main():
	os.popen('adb start-server')
	devicelist = os.popen('adb devices').read()
	devicelist = re.findall(r'(\w+)\s+device\s', devicelist)
	os.popen('adb kill-server')
	curPath = os.getcwd()

	for x in devicelist:
		connect_device("Android://127.0.0.1:5037/" + x)
	
	# 获取case列表
	print("用例列表:").decode('utf-8').encode('gb2312')
	casePath = "%s\\scripts\\CaseConfig" % curPath
	if os.path.exists(casePath):
		caseList = os.listdir(casePath)
		for i in range(0, len(caseList)):
			print("\t%s.%s" % (i, caseList[i]))
	print("")

	# 选择要执行的case
	while True:
		caseIndex = raw_input(("请选择要执行的用例:").decode('utf-8').encode('gb2312'))
		if caseIndex.isdigit():
			if int(caseIndex) >= len(caseList):
				print(("该选项不存在，请重新输入").decode('utf-8').encode('gb2312'))
			else:
				break
		else:
			print(("请输入数字").decode('utf-8').encode('gb2312'))

	caseName = caseList[int(caseIndex)]
	
	# 运行多个手机设备
	for deviceSerialNo in devicelist:
		set_current(deviceSerialNo)
		airPath = "%s\\scripts\\CaseConfig\\%s" % (curPath, caseName)
		reportPath = "%s\\export\\%s\\%s" % (curPath, deviceSerialNo.replace('\n', ''), caseName.replace('.air', ''))
		filePath = reportPath + "\\"

		# # clean log file
		if os.path.exists(filePath):
			for x in os.listdir(filePath):
				if x == "report":
					continue
				os.remove(filePath + x)

			os.system("rd %s /s /q" % filePath)
			os.system("mkdir %s" % filePath)
		else:
			os.system("mkdir %s" % filePath)

		command = "airtest run %s --log %s" % (airPath, reportPath)
		command = "%s --device Android:///%s" % (command, deviceSerialNo)
		os.system("start cmd.exe /c %s" % command)
		

if __name__ == "__main__":
	main()
